import { onDeactivated, onUnmounted } from 'vue'
import { onMountedOrActivated } from '../onMountedOrActivated'
import { inBrowser } from './../../utils/index'

export let supportsPassive = false

if (inBrowser) {
  try {
    const opts = {}
    Object.defineProperty(opts, 'passive', {
      get () {
        supportsPassive = true
      },
    })
    window.addEventListener('test-passive', null, opts)
  } catch (e) {

  }
  console.log('supportsPassive', supportsPassive)
}

export type UseEventListenerOptions = {
  target?: EventTarget | undefined
  capture?: boolean
  passive?: boolean
}

export function useEventListener (
  type:string,
  listener:EventListener,
  options:UseEventListenerOptions = {},
) {
  if (!inBrowser) {
    return
  }

  const { target = window, passive = false, capture = false } = options

  let attached = false

  const add = () => {
    if (target && !attached) {
      target.addEventListener(
        type,
        listener,
        supportsPassive ? { capture, passive } : capture,
      )
      attached = true
    }
  }
  const remove = () => {
    if (target && attached) {
      target.removeEventListener(type, listener, capture)
      attached = false
    }
  }

  onUnmounted(remove)
  onDeactivated(remove)
  onMountedOrActivated(add)
}
